package com.example.design.sercive.decorator;

import com.example.design.pojo.Order;
import com.example.design.pojo.Products;
import com.example.design.rabbitmq.RabbitMqConfig;
import com.example.design.repo.ProductsRepository;
import jdk.internal.org.objectweb.asm.TypeReference;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

//装饰器模式具体装饰器角色
@Service
public class OrderServiceDecorator extends AbstractOderServiceDecorator {

    //注入delayServiceTime，获取延迟时间
    @Value("${delay.service.time}")
    private String delayServiceTime;

    //注入serviceLevel，获取服务级别
//    @Value("${service.level}")
//    private String serviceLevel;

    //注入ProductsRepository，查询商品信息
    @Resource
    private ProductsRepository productsRepository;

    //注入rabbitTemplate，发送消息
    @Resource
    private RabbitTemplate rabbitTemplate;


    //实现具体更新用户积分和发送红包
    @Override
    protected void updateUserScoreAndSendRedPaper(String productId, int serviceLevel, float price) {
        switch (serviceLevel) {
            case 0:
                //根据价格百分之一更新积分
                int score = Math.round(price) / 100;
                System.out.println("score is " + score);
                //根据商品属性发送红包
                Products products = productsRepository.findByProductId(productId);
                if (products != null && products.getSendRedBag() == 1) {
                    System.out.println("正常处理，为用户发放红包" + productId);
                }
                break;
            case 1:
                MessageProperties messageProperties = new MessageProperties();
                //设置消息过期时间
                messageProperties.setExpiration(delayServiceTime);
                Message message = new Message(productId.getBytes(), messageProperties);
                //向正常队列发送消息
                rabbitTemplate.send("normalExchange", "normalKey", message);
                System.out.println("延迟处理，延迟时间为" + delayServiceTime);
                break;
            case 2:
                System.out.println("暂停服务");
                break;
            default:
                throw new UnsupportedOperationException("serviceLevel is not support");
        }
    }

    //调用payOrder
    public Order decoratorPay(String orderId, int serviceLevel, float price) {
        //调用payOrder
        Order order = super.payOrder(orderId);
        try {
            //调用更新用户积分和发送红包
            this.updateUserScoreAndSendRedPaper(order.getProductId(), serviceLevel, price);
        } catch (Exception e) {
            //todo 重试机制
        }
        return order;
    }
}
